package com.ybkj.daijia.api.weixin.v1;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.WxSetting;
import com.ybkj.daijia.api.weixin.WxMsgType;
import com.ybkj.daijia.api.weixin.WxXmlUtil;
import com.ybkj.daijia.api.weixin.entity.WxBaseMsgEntity;
import com.ybkj.daijia.api.weixin.handler.HandlerFactory;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.OrderNewRushEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.MemberApply;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.OrderCarType;
import com.ybkj.daijia.server.model.Order.OrderCarTypeDetail;
import com.ybkj.daijia.server.model.PhoneSmsRecord;
import com.ybkj.daijia.server.model.Rate;
import com.ybkj.daijia.server.model.WxBind;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberApplyService;
import com.ybkj.daijia.server.service.MemberPaymentsRecordService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.PhoneSmsRecordService;
import com.ybkj.daijia.server.service.RateService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.WxBindService;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha1Hash;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONArray;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;


@Controller
@RequestMapping(value = "wx/v1/")
public class WxController {

    private static final Logger logger = LoggerFactory.getLogger(WxController.class);

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private HandlerFactory handlerFactory;

    @Autowired
    private DriverService driverService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private WxBindService wxBindService;

    @Autowired
    private PhoneSmsRecordService phoneSmsRecordService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private MemberPaymentsRecordService memberPaymentsRecordService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private MemberApplyService memberApplyService;

    @Autowired
    private RateService rateService;

    @Autowired
    private SmsService smsService;

    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody
    String auth(String signature, String timestamp, String nonce, String echostr) {

        WxSetting setting = settingUtils.getWx();

        logger.info("rect  signature = {}, timestamp = {}, nonce = {}, echostr ={} ", signature,
            timestamp, nonce, echostr);

        String[] array = new String[]{setting.getWxToken(), timestamp, nonce};
        Arrays.sort(array);

        StringBuilder sb = new StringBuilder();

        for (String str : array) {
            sb.append(str);
        }

        Sha1Hash sha1 = new Sha1Hash(sb.toString());

        logger.info("sha1: {}", sha1);

        if (sha1.toString().toLowerCase().equals(signature)) {

            return echostr;
        }

        return null;
    }

    @RequestMapping(method = RequestMethod.POST)
    public void post(@RequestBody String requestBody, HttpServletResponse resp)
        throws DocumentException, IOException {

        logger.info("recv requestBody {}", requestBody);

        WxBaseMsgEntity msg = parseXML(requestBody);

        Element respMsg = handlerFactory.handle(msg);
        if (null != respMsg) {
            resp.setContentType("text/plain;charset=utf-8");
            resp.setCharacterEncoding("utf-8");
            PrintWriter out = resp.getWriter();
            out.println(respMsg.asXML());
            IOUtils.closeQuietly(out);
        }
    }

    @RequestMapping(value = "driver/{driverID}")
    public String driverDetail(@PathVariable("driverID") Long driverID, String label, Double lat,
        Double lng, Long t, String wxuser, Model model) {

        //司机信息
        Driver driver = driverService.findOne(driverID);

        //账号绑定信息
        WxBind bind = wxBindService.findByWxuser(wxuser);

        //客服号码
        String phone = companyService.findOne(driver.getCompanyId()).getTelephone();

        model.addAttribute("driver", driver);
        model.addAttribute("lat", lat);
        model.addAttribute("lng", lng);

        if (StringUtils.isNotBlank(label)) {
            try {
                label = URLDecoder.decode(label, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        model.addAttribute("label", label);
        model.addAttribute("t", t);

        double distance = Distance.doubleVal(lat, lng, driver.getLatitude(), driver.getLongitude());
        DecimalFormat df = new DecimalFormat("0.0");
        String distanceStr = String.format("%s 公里 ", df.format(distance));

        model.addAttribute("distanceStr", distanceStr);
        model.addAttribute("phone", phone);
        model.addAttribute("bind", bind);

        return "weixin/driver";
    }

    @RequestMapping(value = "weixinOrder", method = RequestMethod.POST)
    public @ResponseBody
    Result<Order> weixinOrder(Order order, Long t) {

        logger.debug("recv lat:{},lng:{},label:{},driverId:{},clientPhone:{},t:{}",
            order.getClientLatitude(), order.getClientLongitude(), order.getFromPlace(),
            order.getDriverId(),
            order.getClientPhone(), t);

        Result<Order> vo = new Result<Order>();
        vo.setSuccess(false);

        if (null == order.getClientLatitude() || null == order.getClientLongitude() || null == order
            .getDriverId() || StringUtils.isBlank(order.getClientPhone()) || null == t) {
            vo.setMessage("参数错误");
            return vo;
        }

        if (((new Date()).getTime() - (new Date(t)).getTime()) > 1000 * 60 * 30) {
            vo.setMessage("操作已过期，请重新发送");
            return vo;
        }

        Driver driver = driverService.findOne(order.getDriverId());
        if (null == driver) {
            vo.setMessage("服务人员不存在，请选择其他服务人员");
            return vo;
        }

        if (driver.getStatus() != Driver.DRIVER_ONLINE) {
            vo.setMessage("服务人员忙碌中，请选择其他服务人员");
            return vo;
        }

        Passenger passenger = memberService.findOnePassengerByPhone(order.getClientPhone());

        if (null == passenger) {
            vo.setMessage("用户不存在，无法下单");
            return vo;
        }

        if (StringUtils.isBlank(order.getFromPlace())) {
            String place = HttpClientUtil
                .getPlaceByLngAndLat(order.getClientLongitude(), order.getClientLatitude());
            order.setFromPlace(place);
        }

        order.setClientName(passenger.getName());
        order.setFromSource("微信下单");
        order.setServerTime(new Date());
        order.setOrderCarType(OrderCarType.daijia);
        order.setOrderCarTypeDetail(OrderCarTypeDetail.jhdj);

        return orderService.weixinOrder(order, driver, passenger);

    }


    private WxBaseMsgEntity parseXML(String xml) throws DocumentException {

        Element ele = DocumentHelper.parseText(xml).getRootElement();

        String msgType = ele.elementText("MsgType");

        WxMsgType msgTypeEnum = WxMsgType.valueOf(msgType);

        switch (msgTypeEnum) {
            case event:
                return WxXmlUtil.getMsgEvent(ele);
            case image:
                return WxXmlUtil.getMsgImage(ele);
            case link:
                return WxXmlUtil.getMsgLink(ele);
            case location:
                return WxXmlUtil.getMsgLoc(ele);
            case text:
                return WxXmlUtil.getMsgText(ele);
            case video:
                return WxXmlUtil.getMsgVideo(ele);
            case voice:
                return WxXmlUtil.getMsgVoice(ele);
            default:
                // never happens
                break;
        }
        return null;
    }

    /**
     * 历史订单
     */
    @RequestMapping(value = "historyOrder")
    public String historyOrder(String phone,
        @RequestParam(required = false, value = "pager.offset") Integer start,
        @RequestParam(required = false, value = "limit") Integer limit, Model model) {

        Integer page = 0;

        if (null == limit) {
            limit = 10;
        }

        if (null != start) {
            page = start / limit;
        }

        Page<Map<String, Object>> orders = orderService.historyOrderV3(phone, null, page, limit);

        model.addAttribute("orders", orders);

        model.addAttribute("phone", phone);

        return "weixin/historyorder";

    }

    /**
     * 当前订单(今日订单)
     */
    @RequestMapping(value = "todayOrder")
    public String todayOrder(String phone, Model model) {

        List<Order> orders = orderService.todayOrder(phone);

        model.addAttribute("orders", orders);

        return "weixin/todayorder";

    }

    /**
     * 会员消费记录
     */
    @RequestMapping(value = "account")
    public String account(Model model, Long memberId,
        @RequestParam(required = false, value = "pager.offset") Integer start,
        @RequestParam(required = false, value = "limit") Integer limit) {
        Integer page = 0;

        if (null == limit) {
            limit = 10;
        }

        if (null != start) {
            page = start / limit;
        }

        Page<Map<String, Object>> records =
            memberPaymentsRecordService.pagePaymentsByMember(memberId, page, limit);

        model.addAttribute("records", records);
        model.addAttribute("memberId", memberId);

        return "m/account";

    }


    /**
     * 会员消费记录下拉刷新
     */
    @RequestMapping(value = "account2", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getOrder(
        Long memberId,
        @RequestParam(required = false, value = "pager.offset") Integer start,
        @RequestParam(required = false, value = "limit") Integer limit) {
        Integer page = 0;
        if (null == limit) {
            limit = 10;
        }
        if (null != start) {
            page = start / limit;
        }
        Page<Map<String, Object>> records = memberPaymentsRecordService
            .pagePaymentsByMember(memberId, page, limit);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = records.getContent();
        return list;
    }

    @RequestMapping(value = "successes")
    public ModelAndView successes(Model model) {

        ModelAndView mv = new ModelAndView();
        mv.setViewName("weixin/successes");

        return mv;
    }

    @RequestMapping(value = "waiting")
    public ModelAndView waiting(Model model) {

        ModelAndView mv = new ModelAndView();
        mv.setViewName("weixin/waiting");

        return mv;
    }

    /**
     * 优惠券记录
     */
    @RequestMapping(value = "coupon")
    public String coupon(Model model, Long memberId) {
        model.addAttribute("memberId", memberId);
        return "m/coupon";
    }

    @RequestMapping(value = "coupon2", method = RequestMethod.GET)
    public @ResponseBody
    List<Coupon> coupon2(
        Long memberId,
        @RequestParam(required = false, value = "pager.offset") Integer start,
        @RequestParam(required = false, value = "limit") Integer limit) {
        Integer page = 0;
        if (null == limit) {
            limit = 10;
        }
        if (null != start) {
            page = start / limit;
        }
        Page<Coupon> pageCoupons = couponService.queryByPassenger(memberId, page, limit, null);
        List<Coupon> list = new ArrayList<Coupon>();
        list = pageCoupons.getContent();
        return list;
    }

    /**
     * 历史订单
     */
    @RequestMapping(value = "historyOrder2")
    public String historyOrder2(String phone, Model model) {
        model.addAttribute("phone", phone);
        model.addAttribute("bind", wxBindService.findByPhone(phone));
        return "m/historyorder";
    }

    /**
     * 下拉刷新
     */
    @RequestMapping(value = "historyOrder3", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getOrder(String phone,
        @RequestParam(required = false, value = "pager.offset") Integer start,
        @RequestParam(required = false, value = "limit") Integer limit) {
        Integer page = 0;
        if (null == limit) {
            limit = 10;
        }
        if (null != start) {
            page = start / limit;
        }
        Page<Map<String, Object>> orders = orderService.historyOrderV3(phone, null, page, limit);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = orders.getContent();
        return list;
    }

    /**
     * 当前订单(今日订单)
     */
    @RequestMapping(value = "todayOrder2")
    public String todayOrder2(String phone, Model model) {
        model.addAttribute("phone", phone);
        model.addAttribute("bind", wxBindService.findByPhone(phone));
        return "m/dayorder";
    }

    @RequestMapping(value = "todayOrder3", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getTodayOrder(String phone) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Order> orders = orderService.todayOrder(phone);
        SimpleDateFormat SimpleDate = new SimpleDateFormat("HH:mm");
        String orderStatus = "新单";
        for (Order order : orders) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("orderId", order.getId());
            map.put("orderNumber", order.getOrderNumber());
            map.put("fromPlace", order.getFromPlace());
            map.put("created", SimpleDate.format(order.getCreated()));
            map.put("orderBookAddress", order.getFromPlace());
            map.put("hasbeenRate", order.isHasbeenRate());
            switch (order.getStatus()) {
                case 1:
                    orderStatus = "已派单";
                    break;
                case 2:
                    orderStatus = "服务中";
                    break;
                case 3:
                    orderStatus = "已完成";
                    break;
                case 4:
                    orderStatus = "已派单";
                    break;
                case 5:
                    orderStatus = "已销单";
                    break;
                case 6:
                    orderStatus = "已完成";
                    break;
                case 7:
                    orderStatus = "预派单";
                    break;
            }
            map.put("status", orderStatus);
            map.put("orderCarType", order.getOrderCarType());
            map.put("orderTotalCost", order.getRealCash());
            map.put("orderTargetAddress", order.getToPlace());
            map.put("orderIsRate", order.isHasbeenRate());
            map.put("orderDriverId", order.getDriverId());
            map.put("orderDriverPhone", order.getDriverPhone());
            map.put("orderDriverName", order.getDriverName());
            list.add(map);
        }
        return list;
    }

    /**
     * vip申请
     */
    @RequestMapping(value = "askForVIP")
    public String askForVIP(String phone, String membername, Model model) {

        model.addAttribute("phone", phone);
        model.addAttribute("membername", membername);

        return "m/vip";
    }

    /**
     * 公司列表
     */
    @RequestMapping(value = "aboutus")
    public String aboutus(Model model) {

        List<Company> companys = companyService.findAll();

        model.addAttribute("companys", companys);

        return "weixin/aboutus";

    }

    /**
     * @param code
     * @return
     */
    @RequestMapping(value = "userInfo")
    public @ResponseBody
    Result<String> userInfo(String code) {
        Result<String> result = new Result<String>();
        result.setSuccess(false);

        WxSetting setting = settingUtils.getWx();
        String appId = setting.getWxAppId();
        String secret = setting.getWxAppSecret();

        String openId = HttpClientUtil.getUserInfo(code, appId, secret);
        Map<String, String> map = new HashMap<String, String>();

        if (StringUtils.isNotBlank(openId)) {
            WxBind bind = wxBindService.findByWxuser(openId);
            if (null != bind) {
                result.setSuccess(true);
                map.put("phone", bind.getPhone());
                map.put("openId", openId);
                result.setObject(map);
                return result;
            } else {
                map.put("error", "BINDNULL");
                map.put("openId", openId);
                result.setObject(map);
                return result;
            }
        } else {
            map.put("error", "OPENIDNULL");
            result.setObject(map);
            return result;
        }

    }

    /**
     * 客户下单
     */
    @RequestMapping(value = "memberOrder")
    public String memberOrder(Model model) {

        model.addAttribute("setting", settingUtils.getWx());

        return "weixin/memberorder";
    }

    @RequestMapping(value = "getAddress", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getAddress(String city, String keyword) {

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        try {
            JSONArray placesArray = HttpClientUtil.getPlacesByName(keyword, city);
            if (null != placesArray && placesArray.length() > 0) {
                for (int i = 0; i < placesArray.length(); i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("name", placesArray.getJSONObject(i).getString("name"));
                    map.put("lng",
                        placesArray.getJSONObject(i).getJSONObject("location").getDouble("lng"));
                    map.put("lat",
                        placesArray.getJSONObject(i).getJSONObject("location").getDouble("lat"));
                    list.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 短信验证码
     * @param phone
     * @return
     */
//	@RequestMapping(value="sendVcode",method=RequestMethod.GET)
//	public @ResponseBody Result<PhoneSmsRecord> sendVcode(String phone){
//		Company mainCompany = companyService.getMain();
//		
//		Result<PhoneSmsRecord> result=new Result<PhoneSmsRecord>();
//		
//		PhoneSmsRecord phoneSmsRecord=phoneSmsRecordService.findByPhone(phone);
//		
//		if(phoneSmsRecord !=null ){
//			
//			long time= (System.currentTimeMillis()-phoneSmsRecord.getExpired().getTime())/1000; //多少秒
//			
//			if(time<120){//2分内禁止发送
//				result.setErrorcode("0");
//				result.setObject(time);
//				return result;
//			}
//			
//			if(time>=120 && time<30*60){//30分内发送旧的
//				result.setSuccess(true);
//				phoneSmsRecord.setExpired(new Date());
//				phoneSmsRecord.setPhone(phone);
//				phoneSmsRecordService.update(phoneSmsRecord);
//				
//				try{
//					String con="尊敬的用户您好,验证码："+phoneSmsRecord.getVcode();
//					SmsTemplet templet = smsService.findByAlias(mainCompany.getId(), SmsType.customMember);
//					if(templet==null){
//						SmsTemplet smsTemplet=new SmsTemplet();
//						smsTemplet.setCompanyId(mainCompany.getId());
//						smsTemplet.setContent("{content}");
//						smsTemplet.setSmsType(SmsType.customMember);
//						smsService.insertSmsTemplate("给客户发自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//					}
//					if(templet != null && StringUtils.isNotBlank(templet.getContent())){
//						smsService.sendSms(phone, "customMember", "{\"content\":\""+con+"\"}",mainCompany.getId(), 2, mainCompany.getSignName());
//					}
//				}catch(Exception e){}
//				
//				return result;
//			}
//			else{//超过30分 发送新的
//				result.setErrorcode("1");
//				result.setSuccess(true);
//				String newCode=String.valueOf(RandomString.randomNum(4));
//				phoneSmsRecord.setExpired(new Date());
//				phoneSmsRecord.setVcode(newCode);
//				phoneSmsRecord.setPhone(phone);
//				phoneSmsRecordService.update(phoneSmsRecord);
//				try{
//					String con="尊敬的用户您好,验证码："+newCode;
//					SmsTemplet templet = smsService.findByAlias(mainCompany.getId(), SmsType.customMember);
//					if(templet==null){
//						SmsTemplet smsTemplet=new SmsTemplet();
//						smsTemplet.setCompanyId(mainCompany.getId());
//						smsTemplet.setContent("{content}");
//						smsTemplet.setSmsType(SmsType.customMember);
//						smsService.insertSmsTemplate("给客户发自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//					}
//					if(templet != null && StringUtils.isNotBlank(templet.getContent())){
//						smsService.sendSms(phone, "customMember", "{\"content\":\""+con+"\"}",mainCompany.getId(), 2, mainCompany.getSignName());
//					}
//				}catch(Exception e){}
//				return result;
//			}
//		}
//		else{
//			
//			String newCode=String.valueOf(RandomString.randomNum(4));
//			phoneSmsRecord=new PhoneSmsRecord();
//			phoneSmsRecord.setExpired(new Date());
//			phoneSmsRecord.setPhone(phone);
//			phoneSmsRecord.setVcode(newCode);
//			phoneSmsRecordService.save(phoneSmsRecord);
//			
//			try{
//				String con="尊敬的用户您好,验证码："+newCode;
//				SmsTemplet templet = smsService.findByAlias(mainCompany.getId(), SmsType.customMember);
//				if(templet==null){
//					SmsTemplet smsTemplet=new SmsTemplet();
//					smsTemplet.setCompanyId(mainCompany.getId());
//					smsTemplet.setContent("{content}");
//					smsTemplet.setSmsType(SmsType.customMember);
//					smsService.insertSmsTemplate("给客户发自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//				}
//				if(templet != null && StringUtils.isNotBlank(templet.getContent())){
//					smsService.sendSms(phone, "customMember", "{\"content\":\""+con+"\"}",mainCompany.getId(), 2, mainCompany.getSignName());
//				}
//				result.setSuccess(true);
//			}catch(Exception e){}
//			
//			return result;
//		}
//	
//	}

    /**
     * 客户下单
     *
     * @param longitude
     * @param latitude
     * @param place
     * @param clientPhone
     * @param vcode
     * @param wxuser
     * @return
     */
    @RequestMapping(value = "orderData", method = RequestMethod.POST)
    public @ResponseBody
    Result<Order> orderData(Double longitude, Double latitude, String place,
        String clientPhone, String vcode, String wxuser) {

        Result<Order> vo = new Result<Order>();
        vo.setSuccess(false);
        if (null == longitude || null == latitude || StringUtils.isBlank(vcode) || StringUtils
            .isBlank(place) || StringUtils.isBlank(clientPhone)) {
            vo.setMessage("参数错误");
            return vo;
        }

        PhoneSmsRecord wXPhoneRecord = phoneSmsRecordService.findByPhone(clientPhone);

        if (wXPhoneRecord != null) {

            if (((System.currentTimeMillis() - wXPhoneRecord.getExpired().getTime()) / 60 * 1000) > 30) {
                if (StringUtils.equals(vcode, wXPhoneRecord.getVcode())) {
                    try {
                        Order order = new Order();
                        order.setClientLongitude(longitude);
                        order.setClientLatitude(latitude);
                        order.setFromPlace(place);
                        order.setServerTime(new Date());
                        order.setClientPhone(clientPhone);
                        List<Company> list = companyService.findByAreaCityName(
                            HttpClientUtil.getCityByLngAndLat(longitude, latitude));
                        Long companyId = null;
                        if (CollectionUtils.isNotEmpty(list)) {

                            List<Company> notMainCompanys = new ArrayList<Company>();
                            Company cityMainCompany = null;

                            for (Company c : list) {
                                if (!c.isCompanyType()) {
                                    notMainCompanys.add(c);
                                } else {
                                    cityMainCompany = c;
                                }
                            }
                            if (!CollectionUtils.isEmpty(notMainCompanys)) {
                                companyId = notMainCompanys
                                    .get(new Random().nextInt(notMainCompanys.size())).getId();
                            }

                            if (null == companyId) {
                                if (null != cityMainCompany) {
                                    companyId = cityMainCompany.getId();
                                }
                            }
                        }
                        if (null == companyId) {
                            companyId = companyService.getMain().getId();
                        }
                        order.setCompanyId(companyId);
                        order.setOrderCarType(OrderCarType.daijia);
                        order.setOrderCarTypeDetail(OrderCarTypeDetail.jhdj);

                        Passenger passenger = memberService
                            .findOnePassengerByPhone(order.getClientPhone());

                        order = orderService.memberBook(order, wxuser);

                        List<Order> rushOrderList = new ArrayList<Order>();
                        rushOrderList.add(order);
                        OrderNewRushEvent newRushEvent = new OrderNewRushEvent(rushOrderList);
                        applicationEventMulticaster.multicastEvent(newRushEvent);

                        if (null == passenger) {
                            passenger = memberService
                                .findOnePassengerByPhone(order.getClientPhone());
                            ReactorVo rVo = new ReactorVo();
                            rVo.setPassenger(passenger);
                            rVo.setActivityEvent(ActivityEvent.newRegister);
                            ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                            applicationEventMulticaster.multicastEvent(activityCheckEvent);
                        }

                        if (StringUtils.isNotBlank(wxuser)) {

                            wxBindService.deleteByWxuser(wxuser);
                            wxBindService.deleteByPhone(clientPhone);

                            WxBind wxBind = new WxBind();
                            wxBind.setCode(vcode);
                            wxBind.setPhone(clientPhone);
                            wxBind.setStatus(WxBind.WXBIND_STATUS_SUCCESS);
                            wxBind.setWxuser(wxuser);
                            wxBindService.insertRecrod(wxBind);
                        }
                        phoneSmsRecordService.deleteByPhone(clientPhone);

                        vo.setMessage("订单创建成功");
                        vo.setSuccess(true);
                    } catch (Exception e) {
                        logger.error("微信下单", e);
                        vo.setMessage(e.getMessage());

                    }
                } else {
                    vo.setErrorcode("error");
                    vo.setMessage("验证码不匹配");
                }
            } else {

                vo.setErrorcode("outTime");
                vo.setMessage("验证码过期,请重新获取");
            }
        } else {
            vo.setMessage("请点击获取验证码");
            vo.setErrorcode("help");
        }

        return vo;
    }

    @RequestMapping(value = "profile")
    public String profile(Model model, String phone) {

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("phone", phone);
        if (StringUtils.isNotBlank(phone)) {

            Passenger passenger = memberService.findOnePassengerByPhone(phone);
            if (null != passenger) {
                model.addAttribute("passenger", passenger);
                model.addAttribute("couponMoney",
                    couponService.sumMoneyByPassenger(passenger.getId()));
                model.addAttribute("telephone", phone);
            }
        }

        return "m/profile";
    }

    @RequestMapping(value = "bind")
    public String bind(Model model, String returnUrl) throws UnsupportedEncodingException {

        model.addAttribute("setting", settingUtils.getWx());
        if (StringUtils.isNotBlank(returnUrl)) {
            model.addAttribute("hasReturnUrl", true);
            model.addAttribute("returnUrl", URLDecoder.decode(returnUrl, "utf-8"));
        } else {
            model.addAttribute("hasReturnUrl", false);
        }

        return "m/bundling";
    }

    //绑定成功
    @RequestMapping(value = "bundlingInfo", method = RequestMethod.POST)
    public @ResponseBody
    Result<WxBind> bundlingInfo(HttpServletRequest req, String wxuser, String telephone,
        String vcode) {

        Result<WxBind> vo = new Result<WxBind>();
        vo.setSuccess(false);

        PhoneSmsRecord wXPhoneRecord = phoneSmsRecordService.findByPhone(telephone);

        if (wXPhoneRecord != null) {

            if (((System.currentTimeMillis() - wXPhoneRecord.getExpired().getTime()) / 60 * 1000) > 30) {
                if (StringUtils.equals(vcode, wXPhoneRecord.getVcode())) {
                    Passenger passenger = memberService.findOnePassengerByPhone(telephone);

                    if (null == passenger) {
                        passenger = new Passenger();
                        passenger.setType(Passenger.TYPE_PASSENGER);
                        passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_WEIXIN);
                        passenger.setAllowOverdraw(Boolean.FALSE);

                        Company company = companyService.getMain();
                        passenger.setCompanyId(company.getId());
                        passenger.setCompanyName(company.getAbbreviation());
                        Result<Passenger> result = memberService.createPersonal(passenger);

                        if (result.isSuccess()) {
                            ReactorVo rVo = new ReactorVo();
                            rVo.setPassenger(result.getResult());
                            rVo.setActivityEvent(ActivityEvent.newRegister);
                            ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                            applicationEventMulticaster.multicastEvent(activityCheckEvent);
                        }

                    }

                    if (StringUtils.isNotBlank(wxuser)) {

                        wxBindService.deleteByWxuser(wxuser);
                        wxBindService.deleteByPhone(telephone);

                        WxBind wxBind = new WxBind();
                        wxBind.setCode(vcode);
                        wxBind.setPhone(telephone);
                        wxBind.setStatus(WxBind.WXBIND_STATUS_SUCCESS);
                        wxBind.setWxuser(wxuser);
                        wxBindService.insertRecrod(wxBind);
                    }
                    phoneSmsRecordService.deleteByPhone(telephone);
                    vo.setSuccess(true);
                    vo.setObject(telephone);
                    vo.setMessage("成功");

                    req.getSession().setAttribute("weixin_phone", telephone);

                } else {
                    vo.setErrorcode("error");
                    vo.setMessage("验证码不匹配");
                }
            } else {

                vo.setErrorcode("outTime");
                vo.setMessage("验证码过期,请重新获取");
            }
        } else {
            vo.setMessage("请点击获取验证码");
            vo.setErrorcode("help");
        }

        return vo;

    }

    @RequestMapping(value = "photoSize")
    public @ResponseBody
    List<String> photoSize(HttpServletRequest req) throws FileNotFoundException {

        List<String> strlist = new ArrayList<String>();

        String bathPath = WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        File root = new File(bathPath + "/upload/driver");
        File[] files = root.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {

            } else {
                strlist.add("文件" + file.getAbsolutePath());
                try {
                    BufferedImage img = ImageIO.read(file);
                    if (img.getWidth() > 200) {
                        Thumbnails.of(file).size(200, Integer.MAX_VALUE).toFile(file);
                    }
                } catch (IOException e) {
                    strlist.add("eror" + e.getMessage());
                }
            }
        }

        return strlist;

    }

    @RequestMapping(value = "createVip", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<MemberApply> memberApply(
        String name, String phone, String email, String memo, HttpServletRequest req) {
        logger.debug("recv name:{},phone:{},email{},memo{}", name, phone, email, memo);

        Result<MemberApply> result = new Result<MemberApply>();
        result.setSuccess(false);

        Passenger passenger_email = memberService.findOnePassengerByEmail(email);
        if (null != passenger_email) {
            result.setMessage("电子邮件" + email + "已经存在");
            return result;
        }

        Passenger passenger_phone = memberService.findOnePassengerByPhone(phone);
        if (null != passenger_phone) {
            result.setMessage("电话号码" + phone + "已经存在");
            return result;
        }

        if (null != memberApplyService.findByPhone(phone)) {
            result.setMessage("该手机号和邮箱已提交申请，等待审核");
            result.setErrorcode("already");
            return result;
        }

        try {

            MemberApply memberApply = new MemberApply();
            memberApply.setEmail(email);
            memberApply.setMemo(HtmlHelper.html1text(memo));
            memberApply.setName(HtmlHelper.html1text(name));
            memberApply.setPhone(HtmlHelper.html1text(phone));
            memberApply.setType(0);

            memberApplyService.insertRecord(memberApply);

            result.setSuccess(true);

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("内部服务器出错");
            return result;
        }
    }

    /**
     * ¬
     *
     * @param orderId
     * @param phone
     * @return
     */
    @RequestMapping(value = "evaluate")
    public ModelAndView evaluate(Long orderId, String phone) {

        ModelAndView mv = new ModelAndView();
        Order order = orderService.findOne(orderId);
        mv.addObject("driver", driverService.findByPhone(order.getDriverPhone()));
        mv.addObject("passenger", memberService.findOnePassenger(order.getClientId()));
        mv.addObject("orderId", orderId);
        mv.addObject("phone", phone);

        mv.setViewName("m/evaluate");

        return mv;
    }

    @RequestMapping(value = "driverEvaluate", method = RequestMethod.POST)
    public @ResponseBody
    Result<String> driverEvaluate(Float starLevel, String content, Long orderId, String phone) {
        Result<String> result = new Result<String>();
        result.setSuccess(false);

        Order order = orderService.findOne(orderId);
        Passenger passenger = memberService.findOnePassenger(order.getClientId());
        Driver driver = driverService.findByPhone(order.getDriverPhone());
        try {
            Rate rate = new Rate();
            if (StringUtils.isBlank(content)) {
                rate.setContent("这个师傅服务真赞啊，赞一个。");
            } else {
                rate.setContent(content);
            }
            if (passenger == null) {
                rate.setMemberId(0L);
                rate.setMemberName("先生/女士");
            } else {
                rate.setMemberId(passenger.getId());
                rate.setMemberName(passenger.getName());
            }
            rate.setMemberPhone(order.getClientPhone());
            rate.setOrderId(orderId);
            rate.setOrderNumber(order.getOrderNumber());
            rate.setDriverId(driver.getId());
            rate.setDriverName(driver.getName());
            rate.setManager(true);
            if (starLevel == null) {
                rate.setStarLevel(5f);
            } else {
                rate.setStarLevel(starLevel);
            }

            rateService.insertRecord(rate);

            order.setHasbeenRate(true);
            orderService.update(order);
            result.setSuccess(true);
            result.setObject(phone);
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("内部服务器出错");
            return result;
        }

    }

    @RequestMapping(value = "EvaluateSuccesse")
    public ModelAndView EvaluateSuccesse(Model model) {

        ModelAndView mv = new ModelAndView();
        mv.setViewName("m/evaluateend");

        return mv;
    }

    @RequestMapping(value = "choosePag", method = RequestMethod.POST)
    public @ResponseBody
    Result<String> choosePag(String phone, String name) {
        Result<String> result = new Result<String>();
        result.setSuccess(false);
        MemberApply ma = memberApplyService.findByPhone(phone);
        if (null != ma) {
            result.setSuccess(true);
        } else {
            Map<String, String> map = new HashMap<String, String>();
            map.put("phone", phone);
            map.put("name", name);
            result.setObject(map);

        }
        return result;
    }

}
